/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 保管费发放,首页
 */
import React, { Component, Fragment } from "react";
import { connect } from "dva";
import { Form, Button, Table, Row, Col, DatePicker, Select, Spin } from "antd";
import moment from "moment/moment";
import { debounce } from "lodash";
import styles from "../style.less";
import ChangeFeeModal from "../components/modal";
import DistributionRecord from "./DistributionRecord";
import FeeDistribute from "./FeeDistribute";

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { Option } = Select;

@connect(({ loading, dispat, report }) => ({
  dispat,
  report,
  stationing: loading.effects["area/subList"],
  getDistributionList: loading.effects["dispat/getDistributionList"],
  getDistributionDetail: loading.effects["dispat/getDistributionDetail"],
  storageFeeReleaseBatch: loading.effects["dispat/storageFeeReleaseBatch"],
  storageFeeRelease: loading.effects["dispat/storageFeeRelease"],
  storageCheckBalance: loading.effects["dispat/storageCheckBalance"],
}))
@Form.create()
class StorageFeeDistribution extends Component {
  handleSearch = debounce(
    e => {
      e.preventDefault();
      const { dispatch } = this.props;
      const type = "dispat/getDistributionList";

      this.getFormValues(values => {
        dispatch({
          type,
          payload: {
            ...values,
            page: 1,
          },
        });
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );

  handleTableChange = debounce(
    pagination => {
      const { fromValues } = this.state;
      const { dispatch } = this.props;
      const params = {
        page: pagination.current,
        ...fromValues,
      };
      this.setState({ page: pagination.current });

      dispatch({
        type: "dispat/getDistributionList",
        payload: params,
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      mode: ["month", "month"],
      selectedRowKeys: [],
      selectedRows: [],
      showGiveOutDetail: false,
      showRecord: false,
      type: null,
      recordValue: {},
      page: 1,
      fromValues: {},
      release_end: moment()
        .subtract("months")
        .format("YYYY-MM-DD"),
      release_start: moment()
        .subtract(2, "months")
        .format("YYYY-MM-DD"),
      confirmLoading: false,
      detailRecord: {}, // 保管费单独发放数据
      allSelectRows: {},
      cm_id: "",
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { page } = this.state;
    this.getFormValues(values => {
      dispatch({
        type: "dispat/getDistributionList",
        payload: {
          page,
          ...values,
        },
      });
    });
  }

  showModal = ({ type, recordValue }) => {
    this.setState({
      visible: true,
      type,
      recordValue,
    });
  };

  handleOk = () => {
    const {
      fromValues: { beginMonth, endMonth },
      page,
      selectedRows,
    } = this.state;
    const { dispatch } = this.props;
    this.setState({ confirmLoading: true });

    const slectedKeys = selectedRows.map(item => item.to_kb_id);

    dispatch({
      type: "dispat/storageFeeReleaseBatch",
      payload: {
        toKbIds: slectedKeys.join(","),
        beginMonth,
        endMonth,
      },
    })
      .then(() => {
        this.getFormValues(value => {
          dispatch({
            type: "dispat/getDistributionList",
            payload: {
              page,
              ...value,
            },
          });
        });
        this.setState({
          confirmLoading: false,
          visible: false,
          selectedRowKeys: [],
          allSelectRows: {},
        });
      })
      .catch(() => {
        this.setState({ confirmLoading: false });
      });
  };

  handleCancel = () => {
    this.setState({
      visible: false,
      confirmLoading: false,
    });
  };

  onSelectChange = (selectedRowKeys, selectedRows) => {
    const { allSelectRows, page } = this.state;

    const allRowsObj = Object.assign(allSelectRows, { [page]: selectedRows });

    const allRowsArr = []; // 每页被选中的行的数据
    for (const key in allRowsObj) {
      if (allRowsObj.hasOwnProperty(key)) {
        const element = allRowsObj[key];
        allRowsArr.push(...element);
      }
    }

    this.setState({
      selectedRowKeys,
      selectedRows: allRowsArr,
      allSelectRows: Object.assign(allSelectRows, { [page]: selectedRows }),
    });
  };

  handlePanelChange = (value, mode) => {
    this.setState({
      release_start: moment(value[0]),
      release_end: moment(value[1]),
      mode: [mode[0] === "date" ? "month" : mode[0], mode[1] === "date" ? "month" : mode[1]],
    });
  };

  hideGiveOut = () => {
    this.setState({
      showGiveOutDetail: false,
    });
  };

  showRecord = () => {
    // 展示保管费发放记录
    this.setState({ showRecord: true });
  };

  hideRecord = () => {
    this.setState({ showRecord: false });
  };

  saveFormRef = formRef => {
    this.formRef = formRef;
  };

  getFormValues = then => {
    const { form } = this.props;
    const format = "YYYY-MM";
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      const { date } = fieldsValue;
      if (date) {
        values.date = date.map(d => moment(d).format(format));
        const [start, end] = values.date;
        values.beginMonth = start;
        values.endMonth = end;
        delete values.date;
      }
      this.setState({
        fromValues: values,
      });
      then(values);
    });
  };

  // 驿站下拉
  getStationList = visible => {
    if (!visible) return;
    const { dispatch } = this.props;
    dispatch({
      type: "report/getYzList",
      payload: "",
    });
  };

  onFilterOperator = (inputValue, options) => {
    const { children } = options.props;
    if (children.indexOf(inputValue) >= 0) return true;
  };

  selectCurrency = (e, labe) => {
    this.setState({
      cm_id: labe.props.value,
    });
  };

  changeSelect = value => {
    if (!value) {
      this.setState({
        cm_id: "",
      });
    }
  };

  checkEmpty = value => {
    if (value == null || value == "null" || value == undefined || value == "") {
      return "";
    } else {
      return value;
    }
  };

  showGiveOut(record) {
    this.setState({
      showGiveOutDetail: true,
      detailRecord: record,
    });
  }

  render() {
    const {
      selectedRowKeys,
      selectedRows,
      visible,
      mode,
      showGiveOutDetail,
      type,
      recordValue,
      release_end,
      release_start,
      showRecord,
      confirmLoading,
      detailRecord,
      fromValues,
      cm_id,
    } = this.state;
    const {
      form: { getFieldDecorator },
      dispat: { distributionList },
      getDistributionList,
      stationing,
      report,
    } = this.props;
    const { frozen_fee, send_fee, deduct_fee } = distributionList.summery;

    const columns = [
      {
        title: "保管费区间",
        dataIndex: "region",
        key: "region",
      },
      {
        title: "驿站名称",
        dataIndex: "inn",
        key: "to_kb_id",
      },
      {
        title: `冻结金额（${this.checkEmpty(frozen_fee)}元）`,
        dataIndex: "frozen_fee",
        key: "frozen_fee",
      },
      {
        title: `已发放金额（${this.checkEmpty(send_fee)}元）`,
        dataIndex: "send_fee",
        key: "send_fee",
      },
      {
        title: `核减金额（${this.checkEmpty(deduct_fee)}元）`,
        dataIndex: "deduct_fee",
        key: "deduct_fee",
      },
      {
        render: (text, record) => {
          return (
            <Row>
              <Col span={12}>
                <Button type="primary" onClick={this.showGiveOut.bind(this, record)}>
                  发放
                </Button>
              </Col>
            </Row>
          );
        },
      },
    ];

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: record => ({
        disabled: record.frozen_fee == 0,
      }),
    };

    const hasSelected = selectedRowKeys.length > 0;
    const frozenFee = recordValue.frozen_fee || 0;
    const pagination = distributionList.pagination
      ? {
          showQuickJumper: false,
          current: distributionList.pagination.current * 1, // number类型
          total: distributionList.pagination.total * 1,
        }
      : false;

    const yzList = (report && report.yzList) || [];

    return (
      <div style={{ paddingTop: 10 }}>
        {!showGiveOutDetail ? (
          showRecord ? (
            <DistributionRecord hideRecord={this.hideRecord} />
          ) : (
            <Fragment>
              <Form className={styles["search-form"]} layout="inline" onSubmit={this.handleSearch}>
                <Row type="flex" style={{ marginBottom: 24 }} justify="space-between">
                  <Col>
                    <FormItem>
                      {getFieldDecorator("date", {
                        initialValue: [moment(release_start), moment(release_end)],
                      })(
                        <RangePicker
                          allowClear={false}
                          placeholder={["开始月份", "结束月份"]}
                          format="YYYY-MM"
                          mode={mode}
                          onPanelChange={this.handlePanelChange}
                        />
                      )}
                    </FormItem>
                    <FormItem>
                      {getFieldDecorator("cm_id", {
                        initialValue: cm_id,
                      })(
                        <Select
                          onDropdownVisibleChange={this.getStationList}
                          filterOption={this.onFilterOperator}
                          placeholder="全部驿站"
                          showSearch
                          allowClear
                          style={{ width: "200px" }}
                          onSelect={this.selectCurrency}
                          onChange={this.changeSelect}
                        >
                          {stationing ? (
                            <Option disabled value="loading">
                              <Spin />
                            </Option>
                          ) : (
                            <Option key="all" value="">
                              全部驿站
                            </Option>
                          )}
                          {yzList.map(({ cm_id, company_name }) => (
                            <Option key={cm_id} value={cm_id}>
                              {company_name}
                            </Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>
                    <FormItem>
                      <Button
                        type="primary"
                        htmlType="submit"
                        key="search"
                        icon="search"
                        loading={getDistributionList}
                      >
                        查询
                      </Button>
                    </FormItem>
                  </Col>
                  <Col>
                    <Fragment>
                      <FormItem>
                        <Button
                          type="primary"
                          key="give_out_all"
                          disabled={!hasSelected}
                          onClick={() =>
                            this.showModal({
                              type: "giveOutBanch",
                              recordValue: { frozen_fee: selectedRows },
                            })
                          }
                        >
                          批量发放
                        </Button>
                      </FormItem>
                      <FormItem>
                        <Button type="primary" key="record" onClick={this.showRecord}>
                          保管费发放记录
                        </Button>
                      </FormItem>
                    </Fragment>
                  </Col>
                </Row>
              </Form>
              <Table
                loading={getDistributionList}
                rowKey={record => record.to_kb_id}
                dataSource={distributionList.list}
                columns={columns}
                pagination={pagination}
                rowSelection={rowSelection}
                onChange={this.handleTableChange}
              />
            </Fragment>
          )
        ) : (
          <FeeDistribute
            hideGiveOut={this.hideGiveOut}
            detailRecord={detailRecord}
            fromValues={fromValues}
          />
        )}
        <ChangeFeeModal
          type={type}
          frozenFee={frozenFee}
          title="保管费发放"
          wrappedComponentRef={this.saveFormRef}
          visible={visible}
          onCancel={this.handleCancel}
          onCreate={this.handleOk}
          confirmLoading={confirmLoading}
        />
      </div>
    );
  }
}

export default StorageFeeDistribution;
